const router = require("koa-router")();
const fs = require("fs")
const path = require("path")
const main = require("../models")
router.get("/form", async ctx => {
    await ctx.render("form")
})
router.post("/doForm", async ctx => {
    console.log(ctx.request.body);
    var { username, age, sex } = ctx.request.body;
    age = Number(age)
    console.log(username);
    var filename = ctx.request.files.logo.path;
    var reader = fs.createReadStream(filename);
    var uploadFile = `./static/${path.basename(filename)}`;
    var write = fs.createWriteStream(uploadFile);
    reader.pipe(write);
    var logo = ctx.origin + "/" + path.basename(filename);
    console.log(logo);
    const collection = await main('member');
    var res = await collection.find({ username}).toArray();
    console.log(res);
    if (res.length) {
        ctx.body = "<script>alert('已添加过该成员');location.href='/home'</script>"
        
    } else {
        await collection.insertOne({ username, age, sex, logo });
        await ctx.redirect("/home")
    }
    
})
module.exports = router;